package com.example.demo.filter;


import com.example.demo.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

@Slf4j
public class PermissionFilter extends AccessControlFilter {
	@Override
	protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response, Object mappedValue) throws Exception {
		try {
			//先判断带参数的权限判断
			Subject subject = getSubject(request, response);
			Object principal = subject.getPrincipal();
			SysUser user= (SysUser) principal;
//			if(user!=null){
//				//超级管理员有所有权限
//				if("admin".equals(user.getUserName())){
//					return Boolean.TRUE;
//				}
//			}

			HttpServletRequest httpRequest = ((HttpServletRequest)request);

			//获取URI
			String uri = httpRequest.getRequestURI();
			//获取basePath
			String basePath = httpRequest.getContextPath();
			if(null != uri && uri.startsWith(basePath)){
				uri = uri.replaceFirst(basePath, "");
			}

			uri=uri.substring(1, uri.length());
			if(subject.isPermitted(uri)){
				return Boolean.TRUE;
			}else {
				if(uri.split("/").length>2){
					uri=uri.split("/")[0]+"/"+uri.split("/")[1];
					if(subject.isPermitted(uri)){
						return Boolean.TRUE;
					}
				}
			}
			return Boolean.FALSE;
		}catch (Exception e){
			log.error(e.getMessage());
			return Boolean.FALSE;
		}
	}

	@Override
	protected boolean onAccessDenied(ServletRequest request,
                                     ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);
		//表示没有登录，重定向到登录页面
		if (null == subject.getPrincipal()) {
			saveRequest(request);
			WebUtils.issueRedirect(request, response, "/login");
		}else {
			String json = "没权权限访问该资源";
			System.out.println(json);
		}
		return Boolean.FALSE;
	}

}
